<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!--头部公共组件 -->
      <PageTools :showBefore="true">
        <span slot="before">共{{ page.total }}条数据</span>
        <template v-slot:after>
          <el-button
            size="small"
            type="success"
            @click="$router.push('/import')"
          >
            excel导入</el-button
          >
          <el-button size="small" type="danger" @click="exportData"
            >excel导出</el-button
          >
          <el-button size="small" type="primary" @click="showDialog = true"
          :disabled="!checkPermission('')"  >新增员工</el-button
          >
        </template>
      </PageTools>
      <!--/头部公共组件 -->
      <el-card>
        <!-- 表格 -->
        <!-- sortable="" 升序降序 -->
        <el-table v-loading="loading" border="" :data="list">
          <el-table-column type="index" label="序号" sortable="" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="头像" align="center">
            <template slot-scope="{row}">
              <img
               @click="showCodehandle(row.staffPhoto)"
                v-imagerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto "
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                alt=""
              >
            </template>
</el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
            sortable=""
            :formatter="formatEmployment"
          />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <!-- 作用插槽 +过滤器 进行时间格式化 -->
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template slot-scope="obj">
              {{ obj.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>

          <el-table-column label="账户状态" prop="enableState" sortable="">
            <template slot-scope="obj">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="obj.row.enableState === 1"> </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/detail/${row.id}`)" >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" @click="delEmployee(row.id)" size="small"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- /表格 -->
        <!-- 分页器 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :page-size="page.size"
            :current-page="page.page"
            :total="page.total"
            @current-change="changPage"
            layout="prev, pager, next"
          />
        </el-row>
        <!-- /分页器 -->
      </el-card>
    </div>
    <!-- 添加员工对话框 -->
    <!-- sync 修饰符 语法糖 子组件修改父组件数据的语法糖 子组件发出 update事件父组件就能监听到 -->
    <AddEmployee :showDialog.sync="showDialog"></AddEmployee>
    <el-dialog title="二维码" :visible.sync="showCode">
    <el-row type="flex" justify="center">
      <canvas ref="myCanvas"></canvas>
    </el-row>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <AssignRole ref="assignrole" :user-id="userId" :showRoleDialog.sync="showRoleDialog"></AssignRole>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from "@/api/employees";
import EmployeeEnum from "@/api/constant/employees";
import AddEmployee from "./components/add-employee.vue";
import {formatDate} from '@/filters'
import QCode from 'qrcode'
import AssignRole from "./components/assign-role.vue";
import checkPermission from "@/mixin/checkPermission";
export default {
  data() {
    return {
      userId:'',
      loading: false,
      list: [], //接收数据
      page: {
        page: 1, //当前页码
        size: 10, //每页大小
        toal: 0, //总数
      },
      showDialog: false, //新增员工弹层
      showCode:false,//二维码弹出层
      showRoleDialog:false,//分配角色对话框
    
    };
  },
  components: {
    AddEmployee,
    AssignRole
  },
  created() {
    this.getEmployeeList();
  },
  methods: {
    // 组件的方法和接口方法可重名
    async getEmployeeList() {
      this.loading = true;
      // 根据当前页码和每页大小返回每页数据
      const { rows, total } = await getEmployeeList(this.page);
      this.list = rows;
      this.page.total = total; //后端数据更新给前端
      this.loading = false;
    },
    changPage(newPage) {
      this.page.page = newPage; //更新页码
      this.getEmployeeList(); //重新获取数据
    },
    // 格式化聘用形式
    formatEmployment(row, column, cellValue, index) {
      // 要去找 1所对应的值
      const obj = EmployeeEnum.hireType.find((item) => item.id === cellValue);
      return obj ? obj.value : "未知";
    },
    //删除员工
    async delEmployee(id) {
      try {
        await this.$confirm("确认删除？");
        await delEmployee(id);
        this.$message.success("删除成功");
        this.getEmployeeList();
      } catch (err) {
        console.log(err);
      }
    },
    // 数据导出excel表格
    exportData() {
      // 因为数据中的key是英文，想要导出的表头是中文的话，需要将中文和英文做对应
      const headers = {
        姓名: "username",
        手机号: "mobile",

        入职日期: "timeOfEntry",
        聘用形式: "formOfEmployment",
        转正日期: "correctionTime",
        工号: "workNumber",
        部门: "departmentName",
      };
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      import("@/vendor/Export2Excel").then(async (excel) => {
        // 获取所有数据  1页  所有数据
        const { rows } = await getEmployeeList({
          page: 1,
          size: this.page.total,
        });
        const data = this.formatJson(headers,rows)
        excel.export_json_to_excel({
          // header: ['姓名','工资'], //表头 必填
          // data:[['程刚峰',30000],['程刚峰2',40000]], //具体数据 必填
          // filename: "excel-list", //非必填
          // autoWidth: true, //非必填
          // bookType: "xlsx", //非必填
          header: Object.keys(headers), //表头 必填
          data, //具体数据 必填
          filename: "员工信息表", //非必填
          autoWidth: true, //非必填
          bookType: "xlsx", //非必填
          multiHeader,
          merges
        });
      });
      // [{username:'张三，mobile:1341232424'}]=>[[]]
      // 我们要转化数据结构 还要和表头的顺序对上
      // 要求转出的标题是中文。

     
    },
     // [{}]=>[[]]
    formatJson(headers, rows) {
     return  rows.map(item=>{
      return   Object.keys(headers).map(key=>{
        if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            return formatDate(item[headers[key]]) // 返回格式化之前的时间
          } else if (headers[key] === 'formOfEmployment') {
            var en = EmployeeEnum.hireType.find(obj => obj.id === item[headers[key]])
            return en ? en.value : '未知'
          }
         return   item[headers[key]]
        })
      })
    },
    // 显示二维码 对话框
    showCodehandle(url){
      
if(url){
  this.showCode=true
this.$nextTick(()=>{
  QCode.toCanvas(this.$refs.myCanvas,url)
})
}else{
  this.$message.warning('该用户还未上传头像')
}
    },
    // 分配角色
   async  editRole(id){
   this.userId=id
  //  console.log(this.userId);
// 获取到数据之后在显示弹层
// 调用子组件的方法 getUserDetailById
 await this.$refs.assignrole.getUserDetailById(id) //异步的方法所以等待一下
this.showRoleDialog=true

    }
  },
};
</script>

<style>
</style>
